package com.sky.aop;

import com.sky.anno.AutoFillAnnotation;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class AutoFill {

    //设置切点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anno.AutoFillAnnotation)")
    public void pc(){}

    @Around("pc() && @annotation(autoFillAnnotation)")
    public Object autoFill(ProceedingJoinPoint pjp, AutoFillAnnotation autoFillAnnotation) throws Throwable {
        //执行增加的方法->自动填充

        //获取属性
        Object[] args = pjp.getArgs();
        //反射
        Class aClass = args[0].getClass();

        //内省
            //获取对象
        BeanInfo beanInfo = Introspector.getBeanInfo(args[0].getClass());

        OperationType value = autoFillAnnotation.value();

        if(value == OperationType.INSERT ){


//内省
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            Arrays.stream(descriptors).forEach(s->{
                if(s.getName().contains("createTime")){

                }
            });
            Field createTimeField = aClass.getDeclaredField("createTime");
            createTimeField.setAccessible(true);
            createTimeField.set(args[0],LocalDateTime.now());

            Field createUserField = aClass.getDeclaredField("createUser");
            createUserField.setAccessible(true);
            createUserField.set(args[0], BaseContext.getCurrentId());

        }


        Field updateTimeField = aClass.getDeclaredField("updateTime");
        updateTimeField.setAccessible(true);
        updateTimeField.set(args[0],LocalDateTime.now());

        Field updateUserField = aClass.getDeclaredField("updateUser");
        updateUserField.setAccessible(true);
        updateUserField.set(args[0], BaseContext.getCurrentId());

        Object proceed = pjp.proceed();
        return proceed;
    }
}
